
package com.sfdlJPush.controller;

import java.util.HashSet;
import java.util.Set;

import android.app.Instrumentation;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.sfdlJPush.R;
import com.sfdlJPush.api.GetLatestAppVersionRequest;
import com.sfdlJPush.api.GetLatestAppVersionResponse;
import com.sfdlJPush.controller.api.ApiListenrDefaultImpl;
import com.sfdlJPush.controller.api.B5MBaseResponse;
import com.sfdlJPush.utils.B5MActivityHelper;
import com.sfdlJPush.utils.B5MDialog;
import com.sfdlJPush.utils.B5MToaster;
import com.sfdlJPush.utils.SDCardUtil;
import com.sfdlJPush.utils.UpgradeAsyncHttpClient;
import com.sfdlJPush.utils.UserInfoManage;

public class MainActivity extends B5MBaseActivity
{
    private FragmentManager mFragmentManager;
    private MainFragment currentMainFragment;
    private View normal_head;
    private ViewGroup fl_main_head;
    private TextView tv_head_title;
    private ImageView bt_head_left, bt_head_right;
    private GetLatestAppVersionRequest mGetLatestAppVersionRequest;
    protected String downloadUrl;
    protected B5MDialog b5mDialog;
    protected B5MDialog b5mDialog_upgrade;
    protected UpgradeAsyncHttpClient upgradeAsyncHttpClient;

    @Override
    public int doGetContentViewId()
    {
        // TODO Auto-generated method stub
        return R.layout.main;
    }

    @Override
    public void doInitSubViews(View containerView)
    {
        // TODO Auto-generated method stub
        fl_main_head = (ViewGroup) findViewById(R.id.fl_main_head);
    }

    @Override
    public void doInitDataes()
    {
        // TODO Auto-generated method stub
        mFragmentManager = getSupportFragmentManager();
        if (JPushInterface.isPushStopped(getApplicationContext()))
        {
            JPushInterface.resumePush(getApplicationContext());
        }
        Set<String> set = new HashSet<String>();
        //        set.add(UserInfoManage.getInstance().);
        JPushInterface.setAliasAndTags(getApplicationContext(), UserInfoManage.getInstance().getUser().username, set, new TagAliasCallback()
        {
            @Override
            public void gotResult(int arg0 , String arg1 , Set<String> arg2)
            {
                // TODO Auto-generated method stub
                System.out.println("gotResult:" + arg0 + " " + arg1 + " " + arg2);
            }
        });
        replaceFragment(MessageHistoryFragment.class);
        B5MAppManager.getInstance().addActivity(this);
        mGetLatestAppVersionRequest = new GetLatestAppVersionRequest(new ApiListenrDefaultImpl()
        {
            @Override
            public void onSuccess(B5MBaseResponse b5mBaseResponse)
            {
                // TODO Auto-generated method stub
                super.onSuccess(b5mBaseResponse);
                GetLatestAppVersionResponse getLatestAppVersionResponse = (GetLatestAppVersionResponse) b5mBaseResponse;
                if (getLatestAppVersionResponse != null && getLatestAppVersionResponse.version != null && getLatestAppVersionResponse.version.upgrade)
                {
                    downloadUrl = getLatestAppVersionResponse.version.download_url;
                    if (b5mDialog == null)
                    {
                        b5mDialog = B5MDialog.createNoTitleConfirmDialog(mContext);
                        b5mDialog.setContent("发现新版本，是否现在更新？");
                        b5mDialog.setOnLeftButtonClickListener(upgradeOnClickListener);
                    }
                    if (!b5mDialog.isShowing())
                    {
                        b5mDialog.show();
                    }
                }
            }
        }, null);
    }
    private OnClickListener upgradeOnClickListener = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            b5mDialog.dismiss();
            if (!SDCardUtil.isSDCardMouted())
            {
                B5MToaster.showShort(mActivity, "SD卡未装载好", 0);
                return;
            }
            if (b5mDialog_upgrade == null)
            {
                b5mDialog_upgrade = new B5MDialog(mContext, R.layout.dialog_upgrade);
                b5mDialog_upgrade.setTitle("版本更新");
                b5mDialog_upgrade.bt_left.setVisibility(View.GONE);
                b5mDialog_upgrade.setOnRightButtonClickListener(cancelUpdateOnClickListener);
            }
            if (!b5mDialog_upgrade.isShowing())
            {
                b5mDialog_upgrade.show();
            }
            upgradeAsyncHttpClient = new UpgradeAsyncHttpClient(b5mDialog_upgrade, mContext);
            upgradeAsyncHttpClient.start(downloadUrl);
        }
    };
    private OnClickListener cancelUpdateOnClickListener = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            if (upgradeAsyncHttpClient != null)
            {
                upgradeAsyncHttpClient.cancel();
            }
            b5mDialog_upgrade.dismiss();
        }
    };

    @Override
    public void doAfter()
    {
        // TODO Auto-generated method stub
        PackageInfo pi = null;
        try
        {
            pi = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
        }
        catch (NameNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mGetLatestAppVersionRequest.version = pi.versionCode + "";
        mGetLatestAppVersionRequest.os = "1";
        mGetLatestAppVersionRequest.type = "2";
        mGetLatestAppVersionRequest.start();
    }

    public void replaceFragment(Class<?> clazz)
    {
        replaceFragment(clazz, null, false);
    }

    public void replaceFragment(Class<?> clazz , Bundle bundle , boolean isFirst)
    {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        MainFragment checkFragment = (MainFragment) mFragmentManager.findFragmentByTag(clazz.getSimpleName());
        if (currentMainFragment != null)
        {
            if (checkFragment == currentMainFragment)
            {
                return;
            }
            //            fragmentTransaction.hide(currentMainFragment);
        }
        //        if (checkFragment == null)
        //        {
        try
        {
            checkFragment = (MainFragment) clazz.newInstance();
            if (bundle != null)
            {
                if (isFirst)
                {
                    checkFragment.setArguments(bundle);
                }
                else
                {
                    checkFragment.setBundle(bundle);
                }
            }
        }
        catch (java.lang.InstantiationException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IllegalAccessException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //        }
        String hashCode = clazz.hashCode() + "";
        fragmentTransaction.replace(R.id.fl_main, checkFragment, hashCode);
        fragmentTransaction.setTransitionStyle(FragmentTransaction.TRANSIT_ENTER_MASK);
        fragmentTransaction.addToBackStack(hashCode);
        fragmentTransaction.commit();
        currentMainFragment = checkFragment;
        replaceHeadView();
        replaceHeadTitle(currentMainFragment);
        replaceHeadRightButton(currentMainFragment);
    }

    private void replaceHeadRightButton(MainFragment currentMainFragment)
    {
        // TODO Auto-generated method stub
        if (bt_head_right == null)
        {
            return;
        }
        if (currentMainFragment instanceof MessageHistoryFragment)
        {
            bt_head_left.setVisibility(View.GONE);
        }
        else
        {
            bt_head_left.setVisibility(View.VISIBLE);
        }
    }

    public void replaceHeadView()
    {
        if (normal_head == null)
        {
            normal_head = getLayoutInflater().inflate(R.layout.normal_head, null);
            tv_head_title = (TextView) normal_head.findViewById(R.id.tv_main_title);
            bt_head_left = (ImageView) normal_head.findViewById(R.id.bt_main_left);
            bt_head_right = (ImageView) normal_head.findViewById(R.id.bt_main_right);
            normal_head.findViewById(R.id.bt_main_left).setVisibility(View.GONE);
        }
        if (fl_main_head.getChildAt(0) == null || fl_main_head.getChildAt(0).getId() != normal_head.getId())
        {
            fl_main_head.removeAllViews();
            fl_main_head.addView(normal_head);
        }
    }

    private void replaceHeadTitle(Fragment fragment)
    {
        // TODO Auto-generated method stub
        if (tv_head_title == null)
        {
            return;
        }
        String title = null;
        if (fragment instanceof MessageHistoryFragment)
        {
            title = "INQUIRY LIST";
        }
        else if (fragment instanceof ViewEnquiryAndReplyFragment)
        {
            title = "INQUIRY DETAIL";
        }
        tv_head_title.setText(title);
    }

    protected void onFragmentResume(Fragment fragment)
    {
        System.out.println("currentMainFragment1=" + fragment.getClass().getSimpleName());
        if (currentMainFragment != fragment)
        {
            currentMainFragment = (MainFragment) fragment;
            System.out.println("currentMainFragment2=" + currentMainFragment.getClass().getSimpleName());
            replaceHeadView();
            replaceHeadTitle(fragment);
            replaceHeadRightButton(currentMainFragment);
        }
    }
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode , KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if (mFragmentManager.getBackStackEntryCount() == 1)
            {
                if ((System.currentTimeMillis() - exitTime) > 2000)
                {
                    Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                    return true;
                }
                else
                {
                    B5MAppManager.getInstance().AppExit(MainActivity.this);
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onHeadButtonClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.bt_main_left:
                inmitateBack();
                break;
            case R.id.bt_main_right:
                logout();
                break;
            default:
                break;
        }
    }

    public void inmitateBack()
    {
        // TODO Auto-generated method stub
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                // 模拟按键
                Instrumentation inst = new Instrumentation();
                inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); //传入不同的keycode就ok了
                //无法模拟HOME按键,因为系统并没有将HOME按键事件传递给application层
            }
        }).start();
    }

    public void logout()
    {
        UserInfoManage.getInstance().clearData();
        B5MAppManager.getInstance().AppExit(this);
        B5MActivityHelper.startActivity(this, LoginActivity.class);
    }
}
